package test.LIfeService;

import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;

import tool.DBUtil;

public class SecondHandZone extends JFrame {
    private JTextField textField1 = new JTextField(); // 物品名称
    private JTextField textField2 = new JTextField(); // 商家名称
    private JTextField textField3 = new JTextField(); // 价格
    private JButton button1 = new JButton("购买");
    private JButton button2 = new JButton("添加");
    private JButton button3 = new JButton("查找");
    private JScrollPane scrollPane;
    private AbstractTableModel tm;
    private String[] titles = {"物品名称", "商家名称", "价格"};
    private Vector vector = new Vector();

    public SecondHandZone() {
        setTitle("二手市场");
        setBounds(100, 100, 800, 600);
        setLayout(new BorderLayout());

        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();
        JPanel panel3 = new JPanel();

        add(panel1, BorderLayout.NORTH);
        add(panel2, BorderLayout.CENTER);
        add(panel3, BorderLayout.SOUTH);

        createTable();
        panel1.add(scrollPane);

        panel2.add(new JLabel("物品名称："));
        textField1.setColumns(10);
        panel2.add(textField1);
        panel2.add(new JLabel("商家名称："));
        textField2.setColumns(10);
        panel2.add(textField2);
        panel2.add(new JLabel("价格："));
        textField3.setColumns(10);
        panel2.add(textField3);

        panel3.add(button1);
        button1.addActionListener(e -> buy());
        panel3.add(button2);
        button2.addActionListener(e -> add());
        panel3.add(button3);
        button3.addActionListener(e -> search());

        fetchDataFromDatabase(); // 初始化时从数据库加载数据

        // 修改窗口关闭事件处理
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            @Override
            public void windowClosing(java.awt.event.WindowEvent windowEvent) {
                // 创建并显示 LIFeService 界面
                LIFeService lifeService = new LIFeService();
                lifeService.setVisible(true);
            }
        });
    }

    private void add() {
        try {
            if (textField1.getText().isEmpty() || textField2.getText().isEmpty() || textField3.getText().isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写所有字段！", "输入错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            String good = textField1.getText();
            String merchant = textField2.getText();
            double price = Double.parseDouble(textField3.getText());

            if (addItem(good, merchant, price) > 0) {
                JOptionPane.showMessageDialog(this, "添加成功！");
            } else {
                JOptionPane.showMessageDialog(this, "添加失败！");
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "输入格式错误，请检查价格是否为有效数字！", "输入错误", JOptionPane.ERROR_MESSAGE);
        }
        fetchDataFromDatabase();
    }

    private void buy() {
        String good = textField1.getText();
        if (buyItem(good) > 0) {
            JOptionPane.showMessageDialog(this, "购买成功！");
        } else {
            JOptionPane.showMessageDialog(this, "购买失败或商品不存在！");
        }
        fetchDataFromDatabase();
    }

    private void search() {
        String good = textField1.getText();
        if (good.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入要查找的物品名称！", "输入错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        fetchDataFromDatabaseByGood(good);
    }

    private int addItem(String good, String merchant, double price) {
        Connection conn = DBUtil.getConnection();
        String sql = "INSERT INTO secondhand (good, merchant, price) VALUES (?, ?, ?)";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, good);
            pstmt.setString(2, merchant);
            pstmt.setDouble(3, price);
            return pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
        }
        return 0;
    }

    private int buyItem(String good) {
        Connection conn = DBUtil.getConnection();
        String sql = "DELETE FROM secondhand WHERE good = ?";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, good);
            return pstmt.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
        }
        return 0;
    }

    private void fetchDataFromDatabase() {
        Connection conn = DBUtil.getConnection();
        String sql = "SELECT * FROM secondhand";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            vector.clear();
            while (rs.next()) {
                Vector row = new Vector();
                row.add(rs.getString("good"));
                row.add(rs.getString("merchant"));
                row.add(rs.getDouble("price"));
                vector.add(row);
            }
            tm.fireTableDataChanged();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
        }
    }

    private void fetchDataFromDatabaseByGood(String good) {
        Connection conn = DBUtil.getConnection();
        String sql = "SELECT * FROM secondhand WHERE good = ?";
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, good);
            ResultSet rs = pstmt.executeQuery();
            vector.clear();
            while (rs.next()) {
                Vector row = new Vector();
                row.add(rs.getString("good"));
                row.add(rs.getString("merchant"));
                row.add(rs.getDouble("price"));
                vector.add(row);
            }
            tm.fireTableDataChanged();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBUtil.closeConnection(conn);
        }
    }

    private void createTable() {
        JTable table;
        tm = new AbstractTableModel() {
            public int getRowCount() {
                return vector.size();
            }

            @Override
            public int getColumnCount() {
                return titles.length;
            }

            @Override
            public String getColumnName(int column) {
                return titles[column];
            }

            @Override
            public Object getValueAt(int rowIndex, int columnIndex) {
                if (!vector.isEmpty()) {
                    return ((Vector) vector.get(rowIndex)).get(columnIndex);
                } else {
                    return null;
                }
            }
        };
        table = new JTable(tm);
        scrollPane = new JScrollPane(table);
        scrollPane.setBounds(0, 0, 540, 150);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            SecondHandZone secondHandZone = new SecondHandZone();
            secondHandZone.setVisible(true);
        });
    }
}



